package com.morpheus.redis.redisson.api.guid;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false, of = { "timestamp", "dataCenterId", "workerId" })
public class SnowIdDTO implements Serializable, Comparable<SnowIdDTO> {
	private static final long serialVersionUID = 5469515960383024351L;
	/**
	 * 注册时的时间戳
	 */
	private Long timestamp;

	/**
	 * 数据中心节点 0~31
	 */
	private Integer dataCenterId;
	/**
	 * 工作节点 0~31
	 */
	private Integer workerId;

	@Override
	public int compareTo(SnowIdDTO dto) {
		long ex = this.timestamp - dto.getTimestamp();
		return ex > 0 ? 1 : -1;
	}

	public long getId() {
		long result = 0x7FFFFFFFFFFFFFFFL & (((0x1FFFFFFFFFFL & this.timestamp) << 22)
				| ((0x3FF & this.dataCenterId) << 12) | (0xFFF & this.workerId));
		return result;
	}

	public static long getTimestamp(long id) {
		long timestamp = id >> 22;
		return timestamp;
	}

	public static String getIdDatetime(long id, String pattern) {
		long timestamp = getTimestamp(id);
		Calendar calendar = Calendar.getInstance(Locale.CHINA);
		calendar.setTimeInMillis(timestamp);
		DateFormat format = new SimpleDateFormat(pattern);
		String result = format.format(calendar.getTime());
		return result;
	}

	public static void main(String[] args) {
		long timeMillis = System.currentTimeMillis();
		System.out.println("timeMillis=" + timeMillis);
		SnowIdDTO snowIdDTO = new SnowIdDTO(timeMillis, 1024, 1201);
		System.out.println(snowIdDTO.getId());
		long timestamp = SnowIdDTO.getTimestamp(snowIdDTO.getId());
		System.out.println(timestamp);
		Calendar calendar = Calendar.getInstance(Locale.CHINA);
		calendar.setTimeInMillis(timestamp);
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		System.out.println(format.format(calendar.getTime()));
	}
}
